"""
Meme 数据模型和操作 (models/meme.py)

处理 Meme 数据的加载、保存和基本查询。
使用 MySQL 数据库作为数据存储。
"""
import uuid
from datetime import datetime
from models.db_models import Upload  # 使用Upload模型替代Meme模型
from models import db_session
import logging

logger = logging.getLogger(__name__)

def load_memes():
    """
    从数据库加载所有 Meme 数据。
    """
    try:
        session = db_session()
        # 查询所有设置了name的Upload记录，这些被视为表情包
        uploads_db = session.query(Upload).filter(Upload.name != None).all()
        memes = [_upload_to_meme_dict(upload) for upload in uploads_db]
        session.close()
        return memes
    except Exception as e:
        logger.error(f"从数据库加载 Meme 数据时出错: {e}")
        return []

def _upload_to_meme_dict(upload):
    """
    将Upload记录转换为Meme字典格式
    """
    meme_dict = upload.to_dict()
    # 添加兼容旧API的字段
    meme_dict["title"] = meme_dict.get("name", "")
    meme_dict["url"] = meme_dict.get("url", "")
    meme_dict["topText"] = meme_dict.get("top_text", "")
    meme_dict["bottomText"] = meme_dict.get("bottom_text", "")
    meme_dict["likes"] = meme_dict.get("likes", 0)
    meme_dict["creator"] = meme_dict.get("createdBy", "")
    return meme_dict

def get_meme_by_id(meme_id):
    """
    根据 ID 查找单个 Meme。
    """
    try:
        session = db_session()
        upload = session.query(Upload).filter(Upload.id == meme_id).first()
        result = _upload_to_meme_dict(upload) if upload else None
        session.close()
        return result
    except Exception as e:
        logger.error(f"根据ID从数据库查询 Meme 时出错: {e}")
        return None

def create_new_meme(title, creator, url, top_text="", bottom_text=""):
    """
    创建一个新的 Meme 数据记录。

    Args:
        title: 标题
        creator: 创建者
        url: 图片 URL
        top_text: 顶部文字 (可选)
        bottom_text: 底部文字 (可选)

    Returns:
        dict: 新 Meme 的数据。
    """
    meme_id = str(uuid.uuid4())
    created_at = datetime.utcnow()
    
    try:
        session = db_session()
        
        # 从URL中提取文件名作为saved_name
        file_name = url.split('/')[-1] if url else f"{str(uuid.uuid4())}.jpg"
        file_path = f"uploads/{file_name}"
        
        # 创建新的上传记录，同时包含表情信息
        new_upload = Upload(
            id=meme_id,
            name=title,
            description="",
            original_name=f"{title}.jpg",
            saved_name=file_name,
            url=url,
            file_path=file_path,
            created_by=creator,
            created_at=created_at,
            top_text=top_text,
            bottom_text=bottom_text,
            likes=0,
            tags=[]
        )
        session.add(new_upload)
        session.commit()
        
        # 转换为字典返回
        meme_dict = _upload_to_meme_dict(new_upload)
        session.close()
        return meme_dict
    except Exception as e:
        logger.error(f"创建新 Meme 到数据库时出错: {e}")
        session.rollback()
        session.close()
        return None 